﻿/// <reference path="jquery.js" />
/// <reference path="custom2.js" />
/// <reference path="errorcode.js" />

//验证类v1.1
//李杰 2013.10.2
//qq:473084
function Validated(id)
{
    if(id)
    {
        Validated.Item[id]=this;
    }
}
Validated.Item={}
//从表单增加规则
//form  jquery表单元素对象，如果省略则使用body元素
/* 
规则对象格式
"name": {
"data": /^.{2,45}$/|function(){}|ture|false,  //支持任何表达式
"complete": "ok",
"error": "广告名称不得少于2个字符",
"normal": "请输入广告名称",
"required": true,  
"remote":true 
}
*/
Validated.prototype={
    rules: {},
    errmsg: "",
    addrule: function(rule)
    {
        for(var key in rule)
        {
            this.rules[key]=rule[o];
        }
        return this;
    },
    remove: function(keys)
    {
        var _t=this;
        keys=keys.split(",");
        $.each(keys,function(i,value)
        {
            if(_t.rules[value])
            {
                delete _t.rules[value];
            }
        });
    },
    refresh: function()
    {
        var _t=this;
        $.each(this.rules,function(k,v)
        {
            if($("#"+k).length==0)
            {
                delete _t.rules[k];
            }
        });
    },
    validate: function(key,val)
    {
        var val=val||$("#"+key).val()||$("#"+key).html().replace(/\s+/img,"");
        var value=this.rules[key];
        if(value["required"]!==false||val)
        {
            var rule=value.data;
            switch(rule.constructor)
            {
                case RegExp:
                    rule=val.match(rule);
                    break;
                case Function:
                    rule=rule(key);
                    break;
            }
            if(rule&&this.rules[key]["remote"]!==false)
            {
                this.succeed(key);
            }
            else
            {
                this.error(key);
            }
            return rule
        }
        return true;
    },
    bind: function(event,func)
    {
        var t=this;
        $.each(this.rules,function(k,v)
        {
            var key=$("#"+k);
            if(key.length)
            {
                key.unbind(event,func);
                key.bind(event,func);
            }
            else
            {
                delete t[k];
            }
        });
        return this;
    },
    event: function(key,event)
    {
        var t=this;
        if(this.rules[key])
        {
            $("#"+key).bind(event,function()
            {
                t.validate(this.id);
            });
        }
    },
    normal: function(key)
    {
        var info=$("[for="+key+"]");
        info.html(this.rules[key]["normal"]||"");
        info.removeClass("succeed");
        info.removeClass("error");
        info.addClass("normal");
        return this;
    },
    onsucceed: function(key)
    {

    },
    succeed: function(key)
    {
        var info=$("[for="+key+"]");
        if(info.length)
        {
            if(info[0].tagName.toLowerCase()!="input")
            {
                info.html("&nbsp;"+(this.rules[key].complete||""));
            }
            info.removeClass("error");
            info.removeClass("normal");
            info.addClass("succeed");
        }
        this.rules[key]["succeed"]=true;
        this.onsucceed(key);
        return this;
    },
    onerror: function(key)
    {

    },
    error: function(key,msg)
    {
        var info=$("[for="+key+"]");
        msg=msg||this.rules[key]["remotemsg"]||this.rules[key].error||"出错了！";
        if(info.length)
        {
            this.infoval(info,msg);
            info.removeClass("succeed");
            info.removeClass("normal");
            info.addClass("error");
            this.rules[key]["succeed"]=false;
        }
        else
        {
            alert(msg);
        }
        this.onerror(key,msg);
        return this;
    },
    remote: function(key,status,msg)
    {
        this.rules[key]["remotemsg"]=msg;
        switch(arguments.length)
        {
            case 1:
                this.rules[key]["remote"]=false;
                break;
            case 2:
                this.rules[key]["remote"]=status;
                break;
            case 3:
                if(status)
                {
                    this.succeed(key);
                    this.rules[key]["remote"]=true;
                }
                else
                {
                    this.error(key,msg);
                }
                break;
        }
    },
    infoval: function(info,msg)
    {
        info.addClass("normal");
        if(info[0].tagName.toLowerCase()=="input")
        {
            info.val(msg||"");
        }
        else
        {
            info.html(msg||"");
        }
    },
    initdef: function()
    {
        for(var key in this.rules)
        {
            var info=$("[for="+key+"]");
            if(this.rules[key]["def"]&&info.length)
            {
                this.infoval(info,this.rules[key].normal);
            }
        }
        return this;
    },
    blur: function()
    {
        var _t=this;
        this.bind("blur",function()
        {
            _t.validate(this.id);
        });
        return this;
    },
    focus: function()
    {
        var _t=this;
        this.bind("focus",function()
        {
            _t.normal(this.id);
        });
        return this;
    },
    ajaxverify: function(params,url)
    {
        var t=this;
        url=url||"/data/ajaxverify.aspx";
        params=params||{};
        if(Cookie.Get("usertoken"))
        {
            params["usertoken"]=Cookie.Get("usertoken");
        }
        $.post(url,params,function(data)
        {
            data=data.toJson();
            if(t.onajaxverify)
            {
                t.onajaxverify(data);
            }
            else
            {
                t.remote(data["jsonmarker"],data["data"],errorcode[data["data"]]);
            }
        });
        return this;
    },
    onajaxverify: null,
    //完整的验证，即验证指定或所有的
    complete: function(keys)
    {
        this.refresh();
        var len=arguments.length;
        if(len)
        {
            for(var i=0;i<len;i++)
            {
                if(!this.validate(arguments[i])||this.rules[arguments[i]]["remote"]===false)
                {
                    this.errmsg=this.rules[arguments[i]].error;
                    return false;
                }
            }
        }
        else
        {
            for(var key in this.rules)
            {
                if(!this.validate(key)||this.rules[key]["remote"]===false)
                {
                    this.errmsg=this.rules[key].error;
                    return false;
                }
            }
        }
        return this.oncomplete();
    },
    oncomplete: function()
    {
        return true;
    },
    trigger: function(el,event)
    {
        var _t=this;
        $(el).bind(event,function(e)
        {
            if(!_t.complete())
            {
                e.preventDefault();
            }
        });
    }
}
Validated.mailrule=/^[\w\.\-_]{1,20}@(?:[\w\-]{1,10}){1,3}(?:\.[\w\-]{1,10}){1,3}$/img;
Validated.phonerule=/^1[1-9]\d{9}$/;
Validated.fixedphonerule=/^\d{3,4}-?\d{7,8}-?\d{0,8}$/;
Validated.qqrule=/^[1-9]\d{5,12}$/;
Validated.idcardrule=/^\d{17,18}X?$/i;
Validated.riqirule=/^\d{4}-?\d{2}-?\d{2}$/;
Validated.photorule=/(jpg|png|jpeg)$/;
Validated.pwdrule=/^.{6,}$/;

Validated.Rules={};  //规则集

Validated.number=function(val,min,max)
{
    return val.constructor==Number&&val>=min&&val<=max;
}
Validated.numberkey=function(key,min,max)
{
    var el=$("#"+key);
    var min=el.attr("min")?parseFloat(el.attr("min")):min;
    var max=el.attr("max")?parseFloat(el.attr("max")):max;
    var val=parseFloat(el.val());
    return Validated.number(val,min,max);
}
Validated.money=function(key)
{
    return Validated.numberkey(key,-Math.pow(10,12)+1,Math.pow(10,12)-1);
}
Validated.tinyint=function(key)
{
    return Validated.numberkey(key,0,255);
}
Validated.smallint=function(key)
{
    return Validated.numberkey(key,-32768,32767);
}
Validated.int=function(key)
{
    return Validated.numberkey(key,-2147483648,2147483647);
}
Validated.bigint=function(key)
{
    return Validated.numberkey(key,-9223372036854775808,9223372036854775807);
}
Validated.float=function(key)
{
    var t=Math.pow(10,38);
    return Validated.numberkey(key,-t+1,t-1);
}
Validated.datetimekey=function(key,min,max)
{
    var el=$("#"+key);
    var min=el.attr("min")||min;
    var max=el.attr("max")||max;
    var val=Date.parse(el.val());
    return Validated.number(val,Date.parse(min),Date.parse(max));
}
Validated.datetime=function(key)
{
    return Validated.datetimekey(key,"1700-01-01","9999-12-30");
}
Validated.string=function(val,minlength,maxlength)
{
    return new RegExp("^\.{"+minlength+","+maxlength+"}$","img").test(val);;
}
Validated.varcharkey=function(key,minlength,maxlength)
{
    var el=$("#"+key);
    var min=el.attr("minlength")||minlength;
    var max=el.attr("maxlength")||maxlength;
    return Validated.string(el.val(),min,max);
}
Validated.varchar=function(key)
{
    return Validated.varcharkey(key,0,4000);
}
Validated.idcard=function(key)
{
    return $("#"+key).val().match(Validated.idcardrule);
}
$("[inputvalidate]").click(function()
{
    var t=$(this);
    var id=t.attr("inputvalidate");
    var thisform=$("#"+id);
    if(!thisform.length)
    {
        return;
    }
    var els=thisform[0].elements;
    var len=els.length;
    var validate=Validated[id];
    var keys=[];
    for(var i=0;i<len;i++)
    {
        if(els[i].id)
            keys.push(els[i].id);
    }
    validate.complete(keys);
});
$(document).ready(function()
{
    $("[submitvalidate]").each(function()
    {
        var t=$(this);
        var thisform=$(t.attr("submitvalidate"));
        if(!thisform.length)
        {
            return;
        }
        var validate=new Validated();

        var els=thisform[0].elements;
        var len=els.length;
        var id=null;
        for(var i=0;i<len;i++)
        {
            id=els[i].id;
            if(Validated.Rules[id])
            {
                validate.rules[id]=Validated.Rules[id];
            }
        }
        validate.focus().blur();
        validate.trigger(t,"click")
    });
});

//输入限定
var allowinput={};
allowinput["number"]=function(e)
{
    var val=e.target.value;
    if(e.which==189)
    {
        return !val.match(/^-[\d\.]*$/);
    }
    return (e.which>47&&e.which<58)||(e.which>95&&e.which<106)
}
allowinput["real"]=function(e)
{
    if(e.which==110)
    {
        return !e.target.value.match(/\./img);
    }
    return this.number(e)||e.which==190;
}
allowinput["time"]=function(e)
{
    return this.number(e)||e.which==59;
}
allowinput["money"]=function(e)
{
    return this.real(e);
}
allowinput["idcard"]=function(e)
{
    return this.number(e)||e.which==88;
}
$("[allowinput]").each(function()
{
    var t=$(this);
    t.keydown(function(e)
    {
        return e.which==8||e.which==9||e.which==13||e.which==46||(e.which>36&&e.which<41)||allowinput[t.attr("allowinput")](e);
    });
})
